package com.hj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hj.mapper.StudentMapper;
import com.hj.pojo.HttpResult;
import com.hj.pojo.Student;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {

        @Resource
        private StudentMapper studentMapper;


        @GetMapping("/all")
        public List<Student> all(){
                List<Student> students = studentMapper.selectList(null);
                return students;
        }

        @DeleteMapping("del/{sid}")
        public HttpResult del(@PathVariable Integer sid){
                HttpResult result = new HttpResult("删除成功", 200, null);
                QueryWrapper<Student> wrapper = new QueryWrapper<>();
                wrapper.eq("sid", sid);
                studentMapper.delete(wrapper);  //逻辑删除，数据表中的deleted字段值变为：1
                return result;
        }

        @PutMapping("/u1")
        public String update1(){
                UpdateWrapper<Student> uw = new UpdateWrapper<>();
                uw.lambda().eq(Student::getSid, 84).setSql("major='外语'");
                studentMapper.update(null, uw);
                return "OOK....";
        }

        @GetMapping("/q1")
        public List<Student>q1(){
                List<Student> students = null;
                QueryWrapper<Student> qw = new QueryWrapper<>();
                qw.lambda().like(Student::getSname, "张");
                students = studentMapper.selectList(qw);
                return students;
        }

        @GetMapping("/q2")
        public List<Map<String,Object>> q2(){
                QueryWrapper<Student> qw = new QueryWrapper<>();
                qw.select("gender,avg(age) as avgAge","count(*) as count").lambda().groupBy(Student::getGender);
                List<Map<String,Object>> lst = studentMapper.selectMaps(qw);
                return lst;
        }

        @PostMapping("/add")
        public HttpResult add(@RequestBody Student student){
                HttpResult result = new HttpResult();
                studentMapper.insert(student);
                result.setMessage("添加成功");
                return result;
        }
        @DeleteMapping("/delete/{sid}")
        public HttpResult delete(@PathVariable Integer sid){
                QueryWrapper<Student> wrapper = new QueryWrapper<>();
                wrapper.eq("sid", sid);
                studentMapper.delete(wrapper);
                return new HttpResult("删除成功",200,null);
        }
}
